package com.hyl.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * @author hyl
 * @version 1.0
 * @date 2023/1/10-14:18
 */
@Component
public class JdbcConfig {
    /**
     *从db.properties文件读取加载
     */

    @Value("${driver}")
    private String driver;
    @Value("${url}")
    private String url;
    @Value("${username}")
    private String username;
    @Value("${password}")
    private String password;

    /**
     * 获取数据源
     * @return
     */
    @Bean
    public DataSource dataSource(){
        DruidDataSource db=new DruidDataSource();
        db.setDriverClassName(driver);
        db.setUrl(url);
        db.setUsername(username);
        db.setPassword(password);
        return db;
    }

    /**
     * 配置事务管理器，mybatis使用的是jdbc事务
     * @param dataSource
     * @return
     */
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource){
        DataSourceTransactionManager sourceTransactionManager=new DataSourceTransactionManager();
        sourceTransactionManager.setDataSource(dataSource);
        return sourceTransactionManager;
    }
}
